package sufutian.com.paypal;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sufutian.com.google_speech.R;

/**
 * Created by sufutian on 2017/7/4.
 */

// AXKuq1NQsy8EHyFAWJFWCZuvmBxQJgf81MUmS08aH1iXTRXG4ClZlstA4F4_mOemIMM3r-QpLV7Y4SQQ   //shahe

//AT2vZTa5RXRJZTd06TR8x3gPHbd7H_E93MYUaczMJ8UspKV4E9mkIvsdQZPhe89wIJI7EqE7QaJDav5Y   live


public class PayPalActivity extends Activity implements View.OnClickListener, Callback {

    public static final String ENVIRONMENT_PRODUCTION = "live";
    public static final String ENVIRONMENT_SANDBOX = "sandbox";
    public static final String ENVIRONMENT_NO_NETWORK = "mock";


    private static String sanbox = "AXKuq1NQsy8EHyFAWJFWCZuvmBxQJgf81MUmS08aH1iXTRXG4ClZlstA4F4_mOemIMM3r-QpLV7Y4SQQ";

    private static String live = "AT2vZTa5RXRJZTd06TR8x3gPHbd7H_E93MYUaczMJ8UspKV4E9mkIvsdQZPhe89wIJI7EqE7QaJDav5Y";


    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(ENVIRONMENT_PRODUCTION)
            .clientId(live);// 分为沙箱 和live的
    private Button start_paly;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paypal);
        start_paly = (Button) findViewById(R.id.start_paly);
        start_paly.setOnClickListener(this);


        Intent intent = new Intent(this, PayPalService.class);

        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);//设置config

        startService(intent);


    }


    @Override
    protected void onDestroy() {
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_paly:
                onBuyPressed();
                break;
        }
    }


    public void onBuyPressed() {

        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to
        //   - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
        //   - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
        //     later via calls from your server.

        PayPalPayment payment = new PayPalPayment(new BigDecimal("0.01"), "USD", "PayPal支付",
                PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(this, PaymentActivity.class);

        // send the same configuration for restart resiliency
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);

        startActivityForResult(intent, 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirm != null) {
                try {
                    Log.i("paymentExample", confirm.toJSONObject().toString(4));

                    // TODO: send 'confirm' to your server for verification.
                    // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                    JSONObject object = confirm.toJSONObject();
                    if (object.has("response")) {
                        JSONObject response = object.getJSONObject("response");
                        if (response.has("id")) {
                            Toast.makeText(PayPalActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//                            getDetails(response.getString("id"));
                            Log.e("sufutian", "onActivityResult: " + response.toString());
                        }
                    }

                } catch (JSONException e) {
                    Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancel the payment", Toast.LENGTH_SHORT).show();
        } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            Toast.makeText(this, "Payment error", Toast.LENGTH_SHORT).show();
        }
    }


    public void getDetails(String id) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间
                .build();

        String requestUrl = "https://api.sandbox.paypal.com/v1/payments/payment" + "/" + id;

        Request.Builder requestBuilder = new Request.Builder()
                .url(requestUrl)
                .get();

        try {
            client.newCall(requestBuilder.build()).enqueue(this);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        Log.e("sufutian", "onFailure: ");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String string = response.body().string();
        Log.e("sufutian==", "onResponse " + string);
    }
}
